package god.dream.loginfo.dao;

import god.dream.comment.model.Comment;
import god.dream.loginfo.model.LogInfo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class SpringJdbcLogInfoDao extends SimpleJdbcDaoSupport implements
		LogInfoDAO {

	public int insert(LogInfo logInfo) throws DataAccessException {
		String query = "INSERT INTO "
				+ "LOGINFO ( L_ID, L_LOGINID, L_LOGINPW, U_ID) "
				+ "VALUES ( ?, ?, ?, ?)";
		return getSimpleJdbcTemplate().update(query, logInfo.insert());
	}

	public int update(LogInfo logInfo) throws DataAccessException {
		String query = "UPDATE LOGINFO "
				+ "SET L_LOGINID=?, L_LOGINPW=?, U_ID=?, L_ADMIN=? " + "WHERE L_ID=?";
		return getSimpleJdbcTemplate().update(query, logInfo.update());
	}

	public int delete(int id) throws DataAccessException {
		String query = "DELETE FROM LOGINFO WHERE L_ID=?";
		return getSimpleJdbcTemplate().update(query, new Object[] { id });
	}

	public LogInfo findLogInfo(int id) throws DataAccessException {
		String query = "SELECT * " + "FROM LOGINFO WHERE L_ID=?";
		ParameterizedRowMapper<LogInfo> rowMapper = getRowMapper();
		try {
			return getSimpleJdbcTemplate().queryForObject(query, rowMapper,
					new Object[] { id });
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}
	public LogInfo findLogInfoWithLoginId(String loginId) throws DataAccessException {
		String query = "SELECT * " + "FROM LOGINFO WHERE L_LOGINID=?";
		ParameterizedRowMapper<LogInfo> rowMapper = getRowMapper();
		try {
			return getSimpleJdbcTemplate().queryForObject(query, rowMapper,
					new Object[] { loginId });
		} catch (EmptyResultDataAccessException e) {
			return null;
		}
	}

	public List<LogInfo> findLogInfoList() throws DataAccessException {
		String sql = "SELECT * FROM LOGINFO";
		ParameterizedRowMapper<LogInfo> rowMapper = getRowMapper();

		return getSimpleJdbcTemplate().query(sql, rowMapper);
	}

	private ParameterizedRowMapper<LogInfo> getRowMapper() {
		ParameterizedRowMapper<LogInfo> rowMapper = new ParameterizedRowMapper<LogInfo>() {
			public LogInfo mapRow(ResultSet rs, int rownum) throws SQLException {
				LogInfo logInfo = new LogInfo();
				logInfo.setId(rs.getInt("L_ID"));
				logInfo.setLoginId(rs.getString("L_LOGINID"));
				logInfo.setLoginPw(rs.getString("L_LOGINPW"));
				logInfo.setUserId(rs.getInt("U_ID"));
				logInfo.setAdmin(rs.getInt("L_ADMIN"));
				return logInfo;
			}
		};
		return rowMapper;
	}
}
